package com.fatmeraid.service.impl;

import com.fatmeraid.common.exception.FarmException;
import com.fatmeraid.common.result.ResultCodeEnum;
import com.fatmeraid.dao.UserDao;
import com.fatmeraid.domain.User;
import com.fatmeraid.service.RegisterService;
import com.fatmeraid.vo.RegisterVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;

@Service
public class RegisterServiceImpl implements RegisterService {

	@Autowired
	private StringRedisTemplate stringRedisTemplate;

	@Autowired
	private UserDao userDao;
	@Override
	public boolean register(RegisterVo registerVo) {
		// 验证码不能为空
		if (registerVo.getCaptchaCode()== null  ){
			throw new FarmException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_NOT_FOUND);
		}
		// 获取redis中的验证码
		String code = stringRedisTemplate.opsForValue().get(registerVo.getCaptchaKey());
		// 判断验证码是否过期
		if (code == null){
			throw new FarmException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED);
		}
		// 判断验证码是否相同
		if(!registerVo.getCaptchaCode().toLowerCase().equals(code)){
			throw new FarmException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR);
		}
		// 查询用户是否存在
		User user = userDao.selectOneByUsername(registerVo.getUsername());

		// 判断用户是否存在
		if (user != null){
			throw new FarmException(ResultCodeEnum.ADMIN_USER_EXIST);
		}
		//对输入密码进行 MD5 加密（与注册时规则一致）
		String inputEncrypted = DigestUtils.md5DigestAsHex(
				registerVo.getPassword().getBytes(StandardCharsets.UTF_8)
		);

		User user1 = new User();
		user1.setUsername(registerVo.getUsername());
		user1.setPassword(inputEncrypted);

		// 插入用户
		int insert = userDao.insert(user1);

		return insert>0;
	}
}
